/**
 * 数据库操作通用类
 * @type {exports}
 */
var dbUtils = require('./database.connection.utils');
var exp = {};
exp.find = function (condition, filter, callback) {
  if (!condition) {
    console.log('database.dao.utils->find:must has a callback');
    return;
  } else if (!filter) {
    callback = condition;
    condition = filter = {};
  } else if (!callback) {
    callback = filter;
    filter = {};
  }
  dbUtils(function (err, db) {
    if (err) {
      callback ? callback(err) : '';
    } else {
      db.collection('favorite').find(condition, filter, function (err, result) {
        if (err) {
          callback(err);
        } else {
          result.toArray(function (err, items) {
            callback ? callback(err, items) : '';
          });
        }
      });
    }
  });
}

exp.insert = function (data, callback) {
  dbUtils(function (err, db) {
    if (err) {
      callback ? callback(err) : '';
    } else {
      db.collection('favorite').insert(data, {safe: true}, function (err, result) {
        callback ? callback(err, result) : '';
      });
    }
  });
}

exp.update = function (condition, data, upsert, multi, callback) {
  if (!condition || !data) {
    console.log('database.dao.utils->update:must has a condition and data');
    return;
  } else if (typeof upsert === 'function') {
    callback = upsert;
    upsert = false;
    multi = false;
  } else if (typeof multi === 'function') {
    callback = multi;
    multi = false;
  }
  dbUtils(function (err, db) {
    if (err) {
      callback ? callback(err) : '';
    } else {
      db.collection('favorite').update(condition, data, {multi: multi, upsert: upsert}, function (err, result) {
        callback ? callback(err, result) : '';
      });
    }
  });
}

module.exports = exp;
